<template>
  <div class="create-outfit-view">
    <!-- 顶部导航栏 -->
    <div class="header">
      <van-icon name="arrow-left" class="back-button" @click="handleBack" />
      <button class="save-button" ref="saveButton">保存</button>
    </div>

    <!-- 分类选择区域 -->
    <div class="category-section">
      <div
        v-for="category in categories"
        :key="category"
        class="category-item"
        @click="handleCategorySelect(category)"
      >
        <div class="category-icon">
          <img
            :src="`/src/assets/icons/${getCategoryIcon(category)}`"
            alt="分类图标"
          />
        </div>
        <div class="category-name">{{ category }}</div>
      </div>
    </div>
    <div style="padding: 20px 0 20px 0">
      <div id="editor-container"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getCategoryIcon } from "../utils/clothesCategory";
import { useClothesStore } from "../store/clothes";
import { useOutfitStore } from "../store/outfit";
import { showToast } from "vant";

import { App, Frame, Box, PointerEvent, Image } from "leafer-ui";
import { EditorEvent } from "@leafer-in/editor";
import "@leafer-in/editor"; // 导入图形编辑器插件 //
import "@leafer-in/viewport"; // 导入视口插件 (可选)
import "@leafer-in/export";
const router = useRouter();
const route = useRoute();
const clothesStore = useClothesStore();
const outfitStore = useOutfitStore();
const saveButton = ref(null);

const clothesId = ref(route.params.id);

//临时存储app导出实例
const appExportInstance = ref(null);

// 服装分类数据
const categories = ref([
  "上衣",
  "下装",
  "裙子",
  "外套",
  "鞋子",
  "配饰",
  "运动装",
  "家居服",
]);

// 处理返回按钮点击
const handleBack = () => {
  outfitStore.clearTempStorageArray();
  router.back();
};

const handleCategorySelect = (categoryId) => {
  // 为了在分类选择页面获取到当前已添加的衣物项编辑的数据，需要将当前app导出实例存储到临时数组中
  outfitStore.tempStorageArray =
    appInstance.value.tree.toJSON().children[0].children;
  // 导航到新的分类选择页面，传递一级分类ID
  router.push(`/clothes-category/${categoryId}`);
};

// 获取路由参数中的outfitId
const outfitId = ref(route.params.id);
const appInstance = ref(null);
const frameInstance = ref(null);
const isInitialized = ref(false);

onMounted(() => {
  // 避免重复初始化
  if (isInitialized.value) return;
  isInitialized.value = true;

  if (outfitId.value) {
    // 不再清空临时存储数组，而是保留已有数据
    // outfitStore.clearTempStorageArray();
    if (outfitStore.tempStorageArray.length <= 0) {
      outfitStore
        .fetchOutfitDetail(outfitId.value)
        .then((response) => {
          console.log("获取搭配详情:", response);
          const canvasData = JSON.parse(response.canvasData);
          // 确保数据格式正确
          if (canvasData && canvasData[0] && canvasData[0].children) {
            // 获取现有数据的ID集合，用于去重
            const existingIds = new Set(
              outfitStore.tempStorageArray.map((item) => item.id || item._id)
            );

            // 过滤掉已存在的数据项，只添加新的衣物项
            const newItems = canvasData[0].children
              .filter((item) => !existingIds.has(item.id || item._id))
              .map((item) => ({ ...item }));

            console.log("添加新衣物项数量:", newItems.length);

            // 使用展开运算符创建新数组，确保Pinia能够检测到变化
            outfitStore.tempStorageArray = [
              ...outfitStore.tempStorageArray,
              ...newItems,
            ];
          }
          // 确保frameInstance初始化完成后再更新编辑器
          if (frameInstance.value) {
            updateEditorWithClothes();
          } else {
            console.warn("搭配详情数据加载完成但frameInstance未初始化");
            // 如果frameInstance还未初始化，可以稍后在frameInstance初始化后再调用updateEditorWithClothes
          }
        })
        .catch((error) => {
          console.error("获取搭配详情失败:", error);
        });
    } else {
      // 确保frameInstance初始化完成后再更新编辑器
      if (frameInstance.value) {
        updateEditorWithClothes();
      } else {
        // console.warn('outfitId存在但frameInstance未初始化');
      }
    }
  }

  // 获取编辑器容器尺寸
  const width = document.getElementById("editor-container").clientWidth;
  const height = document.getElementById("editor-container").clientHeight;

  // 创建编辑器实例
  const app = new App({
    view: "editor-container",
    fill: "#f8f8f8",
    mobile: true, // 适配移动端
    type: "editor",
    editor: {
      moveable: "gesture",
      resizeable: "gesture",
      rotateable: "gesture",
      lockRatio: true,
      point: { cornerRadius: 0 },
      circle: { width: 16, height: 16 },
      buttonsDirection: "top",
      beforeScale({ target, scaleX, scaleY }) {
        if (target.width * scaleX < 40 || target.height * scaleY < 40) {
          const scale = Math.min(40 / target.width, 40 / target.height);
          return { scaleX: scale, scaleY: scale };
        }
        return true;
      },
    },
  });

  // 保存app实例引用
  appInstance.value = app;

  // 创建页面框架
  const frame = Frame.one(
    {
      fill: "#fff",
      children: [], // 先创建空框架，稍后通过updateEditorWithClothes方法添加元素
    },
    0,
    0,
    width,
    height
  );

  frameInstance.value = frame;
  app.tree.add(frame);

  // 确保frameInstance初始化完成后再更新编辑器
  if (outfitStore.tempStorageArray.length > 0 && frameInstance.value) {
    updateEditorWithClothes();
  } else if (outfitStore.tempStorageArray.length > 0) {
    console.warn("衣物数据存在但frameInstance未初始化");
  }

  // 创建更新编辑器内容的方法
  function updateEditorWithClothes() {
    // 清空当前框架中的子元素
    if (frameInstance.value) {
      frameInstance.value.removeAll();
    }

    // 获取衣物数据
    const clothesItems = outfitStore.tempStorageArray;
    console.log("更新编辑器内容，衣物数量:", clothesItems.length);

    // 为每件衣物创建Image元素
    clothesItems.forEach((clothes, index) => {
      if (clothes && clothes.url && frameInstance.value) {
        const image = Image.one({
          url: clothes.url,
          editable: true,
          width: clothes.width || 100,
          height: clothes.height || null,
          dragBounds: "parent",
          id: clothes.id,
          className: "clothes-item",
          x: clothes.x || 10 + index * 10,
          y: clothes.y || 10,
        });
        console.log(image);

        frameInstance.value.add(image);
      } else if (!frameInstance.value) {
        console.error("frameInstance未初始化");
      }
    });
  }

  // 添加移除按钮到编辑器
  const button = Box.one({
    around: "center",
    fill: "#6c63ff",
    cornerRadius: 16,
    cursor: "pointer",
    children: [{ tag: "Text", fill: "white", text: "删除", padding: [7, 10] }],
  });

  // 添加移除按钮到编辑器按钮组
  app.editor.buttons.add(button);

  // 监听移除按钮点击事件
  button.on(PointerEvent.TAP, () => {
    // 点击删除元素，并取消选择
    const selectedElements = [...app.editor.list]; // 创建副本以避免在循环中修改集合
    selectedElements.forEach((rect) => {
      // 删除临时存储数组中的数据
      const elementId = rect.id || rect.__._id;
      console.log("删除元素ID:", elementId);
      outfitStore.deleteTempOutfit(elementId);
      rect.remove();
    });

    app.editor.target = null;
    // 确保frameInstance初始化完成后再强制更新编辑器
    if (frameInstance.value) {
      updateEditorWithClothes();
    } else {
      console.error("删除元素后，frameInstance未初始化，无法更新编辑器");
    }
  });

  // 保存按钮事件处理
  if (saveButton.value) {
    const handleSave = () => {
      const tempStorageArray = outfitStore.tempStorageArray;
      console.log(
        "保存搭配，衣物ID:",
        tempStorageArray.map((item) => item._id)
      );

      // 检查是否有衣物被添加
      if (tempStorageArray.length === 0) {
        showToast({
          message: "请添加衣物",
          position: "bottom",
        });
        return;
      }

      frameInstance.value.export("jpg").then((result) => {
        if (outfitId.value) {
          outfitStore
            .updateOutfit(outfitId.value, {
              finalOutfitImage: result.data,
              clothesIds: tempStorageArray.map((item) => item.id),
              canvasData: JSON.stringify(
                appInstance.value.tree.toJSON().children
              ),
            })
            .then((response) => {
              // 清空临时存储
              outfitStore.clearTempStorageArray();
              router.push("/outfits");
            })
            .catch((error) => {
              console.error("搭配创建失败:", error);
              showToast({
                message: "搭配创建失败",
                position: "bottom",
              });
            });
        } else {
          outfitStore
            .createOutfit({
              finalOutfitImage: result.data,
              clothesIds: tempStorageArray.map((item) => item.id),
              canvasData: JSON.stringify(
                appInstance.value.tree.toJSON().children
              ),
            })
            .then((response) => {
              // 保存成功后可以选择是否清空临时存储
              // 为了支持继续添加，可以选择不清空
              outfitStore.clearTempStorageArray();
              router.push("/outfits");
            })
            .catch((error) => {
              console.error("搭配创建失败:", error);
              showToast({
                message: "搭配创建失败",
                position: "bottom",
              });
            });
        }
        // 调用创建搭配接口
      });
    };

    saveButton.value.addEventListener("click", handleSave);

    // 保存事件处理函数引用，以便在组件卸载时移除
    saveButton.value._saveHandler = handleSave;
  }
});

// 在组件卸载时清理资源
onUnmounted(() => {
  // 移除保存按钮的事件监听
  if (saveButton.value && saveButton.value._saveHandler) {
    saveButton.value.removeEventListener(
      "click",
      saveButton.value._saveHandler
    );
    delete saveButton.value._saveHandler;
  }

  // 清理编辑器实例
  if (appInstance.value) {
    // 销毁编辑器
    appInstance.value.destroy();
    appInstance.value = null;
  }

  // 重置初始化状态，确保下次进入页面时重新加载
  isInitialized.value = false;
});
</script>

<style scoped>
.create-outfit-view {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
  font-size: 18px;
}

.save-button {
  background-color: #6c63ff;
  color: white;
  border: none;
  padding: 2px 10px;
  border-radius: 20px;
  /* font-size: 16px; */
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.save-button:hover {
  background-color: #5a51d8;
}

/* 分类选择区域 - 横向可滑动 */
.category-section {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none; /* Firefox */
  background-color: #ffffff;
  min-height: 80px;
}

/* 隐藏滚动条但保留功能 */
.category-section::-webkit-scrollbar {
  display: none;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
  padding: 16px;
  gap: 5px;
  /* margin-right: 16px; */
  /* min-width: 80px; */
  /* border-radius: 12px; */
  flex-shrink: 0;
}

.category-item:hover {
  transform: scale(1.05);
  background-color: #f9f9f9;
}

.category-icon {
  /* width: 56px;
  height: 56px; */
  display: flex;
  align-items: center;
  justify-content: center;
  /* margin-bottom: 8px; */
  /* border-radius: 12px; */
}

.category-icon img {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.category-name {
  font-size: 12px;
  color: #000000;
  text-align: center;
}

#editor-container {
  width: 100%;
  height: 570px;
  /* padding: 10px; */
}
</style>
